<template>
    <div class="hello">
        <h1>{{ location.name }}未来24小时天气预</h1>
        <GeoLocation/>
        <div ref="chartContainer" class="chartContainer"></div>
    </div>
</template>

<script>
import axios from "axios";
import * as echarts from 'echarts/core';
import {GridComponent} from 'echarts/components';
import {LineChart} from 'echarts/charts';
import {UniversalTransition} from 'echarts/features';
import {CanvasRenderer} from 'echarts/renderers';

echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition]);
import dayjs from 'dayjs'


import {API_24H, key} from "@/common/constrant";
import {mapActions, mapState} from "vuex";
import GeoLocation from "@/components/GeoLocation";

export default {
    name: 'HelloWorld',
    components: {GeoLocation},
    created() {
        this.getData()
    },
    computed: {
        ...mapState(["location", "hourly"])
    },
    methods: {
        ...mapActions(["updateHourlyActions"]),
        getData() {
            axios.get(API_24H, {
                params: {key, location: this.location['id']}
            }).then(({data}) => {
                let hourData = {fxTime: [], temp: []}
                data.hourly.forEach(({fxTime, temp}) => {
                    hourData['fxTime'].push(fxTime)
                    hourData['temp'].push(temp)
                })
                this.updateHourlyActions(hourData)
                this.initChart(
                    this.hourly['fxTime'].map((data) => dayjs(data).format(("HH"))),
                    this.hourly['temp']
                )
            })
        },
        initChart(xAxiosData, seriesData) {
            let charDom = this.$refs.chartContainer
            let myChart = echarts.init(charDom)
            let option = {
                xAxis: {
                    type: "category",
                    data: xAxiosData
                },
                yAxis: {
                    type: "value"
                },
                series: [
                    {
                        data: seriesData,
                        type: 'line',
                        label: {
                            show: true
                        }

                    }
                ]
            };

            // 使用刚指定的配置项和数据显示图表。
            option && myChart.setOption(option);
        }
    },
    watch: {
        location(newValue, oldValue) {
            this.getData()
            console.log(newValue, oldValue)
        }
    }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.chartContainer {
    margin: 0 auto;
    height: 70vh;
}
</style>
